package com.theta.gateway.infra.common.exception.interceptor;

import java.util.HashMap;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;

import com.theta.gateway.infra.common.base.Result;
import com.theta.gateway.infra.common.exception.BusinessException;
import com.theta.gateway.infra.common.exception.enums.ErrorPatternEnum;
import com.theta.gateway.infra.common.utils.JsonUtil;
import com.theta.gateway.infra.common.utils.StrUtil;
/**
 * @Author: theta
 * @Description:
 *
 *  自定义异常处理
 *  <p>异常时用JSON代替HTML异常信息<p>
 **/
@Slf4j
public class JsonExceptionHandler  extends DefaultErrorWebExceptionHandler {


    public JsonExceptionHandler(ErrorAttributes errorAttributes, 
    		ResourceProperties resourceProperties,ErrorProperties errorProperties, 
    		ApplicationContext applicationContext) {
        super(errorAttributes, resourceProperties, errorProperties, applicationContext);
    }


    /**
     * 获取异常属性
     */
//    @Override
//    protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
//        int code = 500;
//        String message=null;
//        Throwable error = super.getError(request);
//        if (error instanceof BusinessException) {
//        	log.warn("BusinessException..");
//        	BusinessException e=(BusinessException)error;
//            return this.response(Result.error(e, e.getData()));
//        }else if (error instanceof org.springframework.cloud.gateway.support.NotFoundException) {
//        	log.warn("NotFoundException..");
//            code = 404;
//        }
//        return response(code, StrUtil.null2string(message, this.buildMessage(request, error)) );
//    }
    
    

    /**
     * 获取异常属性
     */
    @Override
	protected Map<String, Object> getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) {
		
//		return super.getErrorAttributes(request, options);
		int code = 500;
        Throwable error = super.getError(request);
        log.info("getErrorAttributes:{}",error);
        ErrorPatternEnum errorE=ErrorPatternEnum.getExceptionEnum(error.getMessage());
        if (error instanceof BusinessException) {
        	BusinessException e=(BusinessException)error;
            return this.response(Result.error(e, e.getData()));
        }else if(error instanceof org.springframework.cloud.gateway.support.NotFoundException) {
            code = 404;
//            return this.response(code, message);
        }
        code=errorE==null?code:errorE.getCode();
        return response(code, StrUtil.null2string(errorE==null?null:errorE.getMessage(), this.buildMessage(request, error)) );

	}


	/**
     * 指定响应处理方法为JSON处理的方法
     * @param errorAttributes
     */
    @Override
    protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
        return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
    }


    /**
     * 根据code获取对应的HttpStatus
     * @param errorAttributes
     */
//    @Override
    protected HttpStatus getHttpStatusEnum(Map<String, Object> errorAttributes) {
    	log.info("getHttpStatus----->{}",JsonUtil.toJsonString(errorAttributes));
        HttpStatus status=HttpStatus.OK;
    	try {
    		Integer statusCode=(Integer)errorAttributes.get("status");
        	statusCode = statusCode==null?(int) errorAttributes.get("code"):statusCode;
//            int statusCode = (int) errorAttributes.get("code");
//            return HttpStatus.valueOf(statusCode);
    		status=HttpStatus.valueOf(statusCode);
		} catch (Exception e) {
//			log.error("",e);
		}
    	return status;
    }
    
    @Override
    protected int getHttpStatus(Map<String, Object> errorAttributes) {
    	HttpStatus httpStatus=this.getHttpStatusEnum(errorAttributes);
    	return httpStatus.value();
    }


    /**
     * 构建异常信息
     * @param request
     * @param ex
     * @return
     */
    private String buildMessage(ServerRequest request, Throwable ex) {
        StringBuilder message = new StringBuilder("Failed to handle request [");
        message.append(request.methodName());
        message.append(" ");
        message.append(request.uri());
        message.append("]");
        if (ex != null) {
            message.append(": ");
            message.append(ex.getMessage());
            log.error("JsonExceptionHandler buildMessage {}",ex);
        }
        return message.toString();
    }
    
    


    /**
     * 构建返回的JSON数据格式
     * @param status        状态码
     * @param errorMessage  异常信息
     * @return
     */
    public  Map<String, Object> response(int status, String errorMessage) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", status);
        map.put("success", status==0);
        map.put("msg", errorMessage);
        map.put("data", null);
        log.error("JsonExceptionHandler error msg==> {}",errorMessage);
        return map;
    }
    
    @SuppressWarnings("rawtypes")
	public  Map<String, Object> response(Result result) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", result.getCode());
        map.put("success", result.isSuccess());
        map.put("msg", result.getMsg());
        map.put("data", result.getData());
        log.error("JsonExceptionHandler error msg==> {}",result.getMsg());
        return map;
    }


}